package com.rw.middlewarecar.mq;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rw.middlewarecar.pojo.User;
import com.rw.middlewarecar.utils.SendMailUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;

@Component
public class MQConsumer {

    @Autowired
    private SendMailUtils sendMailUtils;

    @Autowired
    private ObjectMapper objectMapper;


    @RabbitListener(queues = "${app.rabbitmq.queueName1}")
    public void ReceivingQueue1(@Payload String msg, @Header(AmqpHeaders.RECEIVED_ROUTING_KEY) String key) {
        System.out.println("queueName1 - key：" + key + "，context：" + msg);
    }
    @RabbitListener(queues = "${app.rabbitmq.queueName2}")
    public void ReceivingQueue2(String msg) {
        System.out.println("queueName2 - " + msg);

        try {
            final User user = objectMapper.readValue(msg, User.class);
            //这个连接可以放到数据库中进行配置，如果是常用的参数，那么可以加载到redis中
            String url = "http://localhost:8090/car/user/active/"+user.getId();
            String html = "<p>欢迎您注册，请 <a href=\""+url+"\">点击此处激活账号</a></p>";
            sendMailUtils.sendRichMail(user.getEmail(),"激活邮件",html,"");
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }
}
